# -*- coding: UTF-8 -*-
"""
@Project ：data_gateway
@File    ：tasks.py
@IDE     ：PyCharm
@Author  ：zhangyiheng
@Date    ：2025/2/27 23:47
@Describe：数据处理
"""
from celery_app.celery_app import app
from config import Config
import requests
import datetime
import os

@app.task(bind=True, max_retries=0, name='send_alarm_task')
def send_alarm_task(self, detection_data):
    """处理告警发送任务"""
    try:
        # 提取区域数据和检测到的类别信息
        area_id = detection_data["area_id"]
        detected_class = detection_data["detected_class"]
        timestamp = detection_data["timestamp"]

        # 转换时间格式
        dt = datetime.datetime.fromtimestamp(timestamp)
        formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")

        # 构建请求参数
        class_info_list = detected_class if isinstance(detected_class, list) else [detected_class]
        levels = []

        # 遍历所有检测到的类别，获取对应的 level
        for class_name in class_info_list:
            class_info = Config.CLASS_MAPPING.get(class_name, {})
            if class_info and "level" in class_info:
                levels.append(class_info["level"])

        # 如果有 level，取最小的 level（最高优先级）
        final_level = min(levels) if levels else 0

        payload = {
            "msg": f"智能监控系统告警识别到:{class_info_list}",
            **Config.FIXED_PARAMS,
            "level": final_level,  # 使用最高优先级的 level
            "time": formatted_time,
            "camera_id": area_id.upper(),
            "stream_url": ""
        }

        print(f"发送请求:{payload}")

        # 发送请求
        response = requests.post(
            Config.API_ENDPOINT,
            json=payload,
            timeout=5
        )

        response.raise_for_status()

    except Exception as e:
        print(f"告警发送失败: {str(e)}")

    # finally:
    #     # 清理临时文件
    #     if detection_data.get("file") and os.path.exists(detection_data["file"]):
    #         try:
    #             os.remove(detection_data["file"])
    #         except Exception as e:
    #             print(f"清理临时文件失败: {str(e)}")